<?php
require_once("inc.member.php");

$this_title="$vars[member_title] &raquo; ".replace_tag(__("<%title%> Transfer"), array("<%title%>"=>__($vars['mwallet_title'])));
$page_title=replace_tag(__("<%title%> Transfer"), array("<%title%>"=>__($vars['mwallet_title'])));
$content_title=replace_tag(__("<%title%> Transfer"), array("<%title%>"=>__($vars['mwallet_title'])));

if(false){//$r_user['activated']!='y'){
	$msg=__("Your account has not yet been activated and you cannot make a transfer until you do that.")." ".
	replace_tag(__("To activate your account, please click <%link%>here<%/link%>."), array("<%link%>"=>"<a href='".$vars['file']['member']['activate']."'>", "<%/link%>"=>"</a>"));
	$content="<h2>$page_title</h2>".format_err($msg);
	print format_member_page($content, $this_title);
	exit();
}

$td_width=180;



//#####AJAX CALL#####
//ajax check user
if($_GET["aj"] && $_GET["check_user"]){
	if($post_s['uid'] == $r_user['code']){
		$ajmsg = __("You cannot transfer to yourself.");
		$status = 2;
	}else{
		$ajresult = ajax_check_user_by_code($post_d['uid']);
		$ajresult2 = ajax_check_user_by_code($r_user['code']);
		
		if((!is_group_matrix_downline_of($ajresult2['user_detail']['id'], $ajresult['user_detail']['id'])) && (!is_group_matrix_downline_of($ajresult['user_detail']['id'], $ajresult2['user_detail']['id']))){
			$ajmsg=__("The selected User ID is not in your network group.")."<br />";	
		}elseif($ajresult['status'] == 3){
			$ajmsg = replace_tag(__("The Member ID '<%code%>' could not be found."), array("<%code%>"=>$post_d['uid']));
			$status = "2";
		}elseif($ajresult['status'] == 2){
			$ajmsg = replace_tag(__("The Member ID '<%code%>' could not be found."), array("<%code%>"=>$post_d['uid']));
			$status = "2";		
		}elseif($ajresult['status'] == 1){
			$ajmsg = __("Member ID")." '$post_s[uid]', ".__("Username").": {$ajresult['user_detail']['username']}";
			$status = $ajresult['status'];
		}	
	}

	print format_xml(array('status'=>$status, 'msg'=>$ajmsg));
	exit;
}
//#####END AJAX CALL#####

//#####TRANSFER POST#####
if($_POST["__req"]){
	$errmsg=verify_form_data("member_mwallet_transfer", $post_s);
	if(!$errmsg){
		if(!strlen($post_s["password"])){
			$errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("AuthCode")))."<br />\n";
		}else{
			$enc_pass=explode(":", $r_user["ewallet_enc_password"]);
			$salt=$enc_pass[1];
			if(md5($post_s["password"].$salt)!=$enc_pass[0]){
				$errmsg.=__("You have entered an invalid AuthCode.")."<br />\n";
			}
		}
		if($post_s['uid']==$r_user['code']){
			$errmsg.=__("You cannot transfer to yourself.")."<br />\n";
		}elseif(!$r_to=get_user_detail_by_code($post_d['uid'])){
			$errmsg.=replace_tag(__("The Transferee ID of '<%id%>' does not exist."), array("<%id%>"=>$post_h['uid']))."<br />\n";
		}elseif($r_to['status']=='terminated'){
			$errmsg.=replace_tag(__("The Transferee ID of '<%id%>' had been terminated and you cannot transfer to this account."), array("<%id%>"=>$post_h['uid']))."<br />\n";
		}
		
		$ajresult = ajax_check_user_by_code($post_d['uid']);
		$ajresult2 = ajax_check_user_by_code($r_user['code']);
		
		if((!is_group_matrix_downline_of($ajresult['user_detail']['id'], $ajresult2['user_detail']['id'])) && (!is_group_matrix_downline_of($ajresult2['user_detail']['id'], $ajresult['user_detail']['id']))){
			$errmsg.=__("The selected User ID is not in your network group.")."<br />";	
		}

		if(!$errmsg){
			if($r_user['mwallet']<$post_s['_amount']){
				$errmsg.=replace_tag(__("You do not have sufficient <%title%> for this transfer."), array("<%title%>"=>__($vars['mwallet_title'])))."<br />\n".replace_tag(__("<%title%> required: <%x%>"), array("<%title%>"=>__($vars['mwallet_title']), "<%x%>"=>number_format($post_s['_amount'], 2)))."<br />\n".replace_tag(__("<%title%> available: <%x%>"), array("<%title%>"=>__($vars['mwallet_title']), "<%x%>"=>number_format($r_user['mwallet'], 2)))."<br />\n";
			}
		}
	}

	if(!$errmsg){
		$datetime=ndate();
		if(!mysql_query($sql="update $db->users set mwallet=mwallet-$post_s[_amount] where id='$uid' limit 1")){
			$errmsg.=__("We have encountered some error while performing the transfer.")." ".__("You can try again later. If the problem persists, please contact us.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
		}else{
			$transferor_deducted=true;
			if(!mysql_query($sql="update $db->users set mwallet=mwallet+$post_s[_amount] where id='$r_to[id]' limit 1")){
				$errmsg.=replace_tag(__("We have encountered some error while performing the transfer and your <%title%> account has been deducted <%x%>, please contact us."), array("<%title%>"=>__($vars['mwallet_title']), "<%x%>"=>number_format($post_s['_amount'], 2)))."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
				$critical_error.="Error performing transfer when member ID #$uid make a transfer to member ID #$post_s[uid] and the member ID #$uid $vars[mwallet_title] account has been deducted with ".number_format($post_s['_amount'], 2).". Please credit back to this member's $vars[mwallet_title] account.<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
			}else{
				$transferee_credited=true;

				//insert transfer record
				$transfer_descr="Transfer of $vars[currency]".number_format($post_s['_amount'], 2);
				if(!mysql_query($sql="insert into $db->member_mwallet_transfer (to_uid, from_uid, amount, remark, cdate) values ('$r_to[id]', '$uid', '$post_d[_amount]', '$post_d[_remark]', '$datetime')")){
					$critical_error.="Error creating the member transfer record when member ID #$uid make a transfer to member ID #$post_s[uid]. Please manually execute the SQL below to record the transaction:<br />\n<br />\n$sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
				}
			}
		}
		if($transferor_deducted){
			//insert e-stockist record
			if(!mysql_query($sql="insert into $db->member_mwallet_record (uid, type, amount, descr, cdate) values ('$uid', 'd', '$post_d[_amount]', '".AddSlashes("Debited $vars[currency]".number_format($post_s['_amount'], 2)." for transfer to member ID #$post_s[uid]".($post_s['_remark']? "\n\nRemark:\n$post_s[_remark]" : ""))."', '$datetime')")){
				$critical_error.="Error creating the transferor $vars[mwallet_title] record when member ID #$uid make a transfer to member ID #$post_s[uid]. Please manually execute the SQL below to record the transaction:<br />\n<br />\n$sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
			}else{
				$new_eid = mysql_insert_id();
				$last_bal = @mysql_result(mysql_query("select bal from $db->member_mwallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
				if(!$last_bal){
					$last_bal = 0;
				}
				$last_bal -= $post_d['_amount'];
				@mysql_query("update $db->member_mwallet_record set bal='$last_bal' where id='$new_eid' limit 1");
			}
		}
		if($transferee_credited){
			//insert e-stockist record
			if(!mysql_query($sql="insert into $db->member_mwallet_record (uid, type, amount, descr, cdate) values ('$r_to[id]', 'c', '$post_d[_amount]', '".AddSlashes("Credited $vars[currency]".number_format($post_s['_amount'], 2)." for transfer from member ID #".$r_user['code'].($post_s['_remark']? "\n\nRemark:\n$post_s[_remark]" : ""))."', '$datetime')")){
				$critical_error.="Error creating the transferee $vars[mwallet_title] record when member ID #$uid make a transfer to member ID #$post_s[uid]. Please manually execute the SQL below to record the transaction:<br />\n<br />\n$sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
			}else{
				$new_eid = mysql_insert_id();
				$last_bal = @mysql_result(mysql_query("select bal from $db->member_mwallet_record where uid='$r_to[id]' and id!=$new_eid order by id desc limit 1"), 0);
				if(!$last_bal){
					$last_bal = 0;
				}
				$last_bal += $post_d['_amount'];
				@mysql_query("update $db->member_mwallet_record set bal='$last_bal' where id='$new_eid' limit 1");
			}
		}

		if(!$errmsg){
			$msg=replace_tag(__("Your have successfully transferred <%x%> to the member with ID <%id%>."), array("<%currency%>"=>$vars['currency'], "<%x%>"=>number_format($post_s['_amount'], 2), "<%id%>"=>$post_h['uid'], "<%username%>"=>$r_to['username']))."<br />\n";
			$r_user=get_user_detail_by_id($uid);
			$logstr = "Member ID#$r_user[code] has successfully transferred $vars[currency]".number_format($post_s['_amount'], 2)." $vars[mwallet_title] to the member with ID #$post_s[uid] ($r_to[username]).";
		}
	}

	$log_code = 'u-ewt';
	$affected_uid = $uid;
	if($critical_error){
		//log_activity('e', 'u', $uid, 'u', $affected_uid, $log_code, $critical_error);
		$a_sub="$vars[title] - $vars[mwallet_title] Transfer Failure for Member ID #$uid";
		$a_msg="
		<p>Dear admin,</p>
		<p>$critical_error</p>";
		email_admin($a_sub, $a_msg, 'e');
	}elseif($logstr){
		$log_descr = $logstr;
		//log_activity('a', 'u', $uid, 'u', $affected_uid, $log_code, $log_descr);
	}

	$msg=$msg? format_msg($msg) : "";
	$errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
}

$form_fields=array("uid"=>"","_amount"=>"","_remark"=>"");
foreach($form_fields as $field => $default){
 $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
 $dis[$field]=(!$post_s["__req"]? $default : $post_h[$field]);
}

//javascript
ob_start();
?>
<script type='text/javascript' src='<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("fn/fn_number_format.js,common.js,jquery.js,jquery.livequery.js"); ?>'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
	j('form[@name=transfer_form]').submit(function(){
		var confirm_text='<?php echo AddSlashes(__("Transfer <#x#> to member ID #<#id#>.")); ?>\n\n<?php echo AddSlashes(__("Are you sure?")); ?>';
		confirm_text=confirm_text.replace(/\<#x#\>/, number_format(j('input[@name=_amount]').val(), 2)).replace(/\<#id#\>/, j('input[@name=uid]').val());
		if(confirm(confirm_text)){
			j('input[@name=submit_btn]').attr('disabled','disabled');
		}else{
			return false;
		}
	});

	j('input#check_user_btn').click(function(){
		j('span#transferee_text').html('').removeClass('red');
		if(j('input[@name=uid]').val()==''){
			j('span#transferee_text').html('<?php echo AddSlashes(__("Please provide a Member ID!")); ?>').addClass('red');
		}else{
			j(this).attr('disabled','disabled');
			j.ajax({
				url: '<?php echo "$this_file?aj=1&check_user=1"; ?>',
				data: {'uid': j('input[@name=uid]').val()},
				type: 'post',
				dataType: 'xml',
				error: function(){
					j('span#transferee_text').html('<?php echo AddSlashes(__("Error checking...")); ?>').addClass('red');
				},
				success: function(data){
					var mesg='';
					if(j('loggedout', data).text()=='loggedout'){
						mesg='<?php echo AddSlashes(__("You have been logged out.")); ?>';
					}else{
						j(data).find('msg').each(function(){
							mesg+=j(this).text()+' ';
						});
					}
					var status=j(data).find('status').text();
					j('span#transferee_text').html(mesg).addClass(status==1? 'bold' : 'red');
				},
				complete: function(){
					j('input#check_user_btn').attr('disabled','');
				}
			});
		}
	});
});
</script>
<?php
$jvscript = ob_get_contents();
ob_end_clean();

//transfer form
$transfer=($errmsg || $msg? $errmsg.$msg : "").
"
<form name='transfer_form' method='post' action='$this_file'>
<input type='hidden' name='__req' value='1' />
<table class='pbt_table'>
	<tr>
		<td width='$td_width'>".__("To").__(":")." ".__("*")."</td>
		<td><input type='text' name='uid' value=\"$dis[uid]\" $inputbox_style />
		</td>
	</tr>
	<tr>
		<td width='$td_width'>".__("Amount").__(":")." ".__("*")."</td>
		<td><input type='text' name='_amount' value=\"$dis[_amount]\" $inputbox_style /><br />\n".
			replace_tag(__("<%title%> Account Balance: <%x%>"), array("<%title%>"=>__($vars['mwallet_title']), "<%x%>"=>number_format($r_user['mwallet'], 2)))."</td>
	</tr>
	<tr>
		<td width='$td_width'>".__("Remarks").__(":")."</td>
		<td><textarea name='_remark' rows='6' $inputbox_style>$dis[_remark]</textarea></td>
	</tr>
	<tr>
		<td width='$td_width'>".__("AuthCode").__(":")." ".__("*")."</td>
		<td><input type='password' name='password' $inputbox_style /></td>
	</tr>
	<tr>
		<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
		<input type='submit' name='submit_btn' value=\"".__("Transfer")."\" />
		</td>
	</tr>
</table>
</form>";

$content=$inc_wallet_select."<h2>$page_title</h2>".$transfer;
print format_member_page($content, $this_title, $content_title, $inc_jvscript . $jvscript);
?>